package com.eagle.view.activity;

import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import com.eagle.EApplication;
import com.eagle.R;
import com.eagle.support.constants.Constants;
import com.eagle.view.activity.base.BaseCallActivity;
import com.eagle.view.fragment.meeting.FragmentMeeting;
import com.eagle.view.fragment.meeting.FragmentMeetingOperation;
import com.eagle.view.fragment.menu.FragmentMenu;
import com.github.javiersantos.materialstyleddialogs.MaterialStyledDialog;
import com.kinstalk.voip.sdk.EngineSdkCallState;
import com.kinstalk.voip.sdk.EngineSdkUserRole;
import com.kinstalk.voip.sdk.EngineSdkVideoPixelFormat;
import com.kinstalk.voip.sdk.logic.sip.aidl.model.CallInfo;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.FragmentById;
import org.androidannotations.annotations.ViewById;

/**
 * Created by gc on 2017/1/13.
 */
@EActivity(R.layout.activity_video_meeting)
public class MeetingActivity extends BaseCallActivity {

    @FragmentById(R.id.fragment_meeting_menu)
    protected FragmentMenu mFragmentMenu;

    @FragmentById(R.id.fragment_meeting)
    protected FragmentMeeting mFragmentMeeting;

    @FragmentById(R.id.fragment_meeting_operation)
    protected FragmentMeetingOperation mFragmentMeetingOperation;

    @ViewById(R.id.layout_parent)
    protected RelativeLayout mLayoutParent;

    @Extra(Constants.CALL_TYPE_MEETING_ANSWER)
    protected boolean mFromMeetingAnswer;

    @Extra(Constants.ROOM_ID)
    protected String mRoomId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setDarkStatusIcon(true);
        initExplodeTransition();
        String uid = EApplication.getSharedPreferences().getString(Constants.LOGIN_UID, "");
        mCallHelper.uid(uid);
    }

    @AfterViews
    void initView() {
        if (!mFromMeetingAnswer) {
            handlerMeeting(false);
        } else {
            refreshRoomInfo();
            handlerFullscreen(true);
            handlerMeeting(true);
            showLoading();
        }
    }

    /**
     * 处理显示fragment
     */
    private void handlerMeeting(boolean show) {
        if (show) {
            getSupportFragmentManager().beginTransaction().show(mFragmentMeeting).hide(mFragmentMeetingOperation).hide(mFragmentMenu).commitAllowingStateLoss();
        } else {
            getSupportFragmentManager().beginTransaction().show(mFragmentMeetingOperation).hide(mFragmentMeeting).hide(mFragmentMenu).commitAllowingStateLoss();
        }
    }

    /**
     * 创建会议成功
     */
    @Override
    public void onGotMeetingRoomResult(String roomId) {
        super.onGotMeetingRoomResult(roomId);
        mRoomId = roomId;
        mCallHelper.roomId(mRoomId);
        refreshRoomInfo();
        mCallHelper.createMeeting(mRoomId, true);
    }

    /**
     * 收到邀请
     */
    @Override
    public void onGotInviteResult(String roomId, String sender) {
        super.onGotInviteResult(roomId, sender);
        mRoomId = sender;
        mCallHelper.userRole(EngineSdkUserRole.ES_UR_TYPE_SLAVER.swigValue());
        mCallHelper.roomId(sender);
        new MaterialStyledDialog.Builder(this)
                .setHeaderColorInt(R.color.gray_transparent)
                .setDescription("Agreed to join " + sender + " ? ")
                .setPositiveText("OK")
                .setNegativeText("CANCEL")
                .setCancelable(true)
                .onPositive((dialog, which) -> {
                    showLoading();
                    mCallHelper.answerMeetingInvite(sender);
                })
                .show();
    }

    @Override
    public void onCallStateHandler(CallInfo call, int state) {
        super.onCallStateHandler(call, state);
        switch (EngineSdkCallState.swigToEnum(state)) {
            case ES_STATE_ON_CALL_IN_ACTIVE_SESSION:
                dismissLoading();
                handlerFullscreen(true);
                new Handler().postDelayed(() -> {
                    mFragmentMeetingOperation.dismissLoading();
                    handlerMeeting(true);
                }, 500);
                break;
            case ES_STATE_ON_CALL_CALL_ENDED:
                //挂断
                dismissLoading();
                mFragmentMeeting.stopCameraPreview();
                new Handler().postDelayed(() -> finish(), 300);
                break;
        }
    }

    private void handlerFullscreen(boolean fullscreen) {
        if (fullscreen) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            mLayoutParent.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
            WindowManager.LayoutParams params = getWindow().getAttributes();
            params.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            getWindow().setAttributes(params);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            setDarkStatusIcon(true);
            WindowManager.LayoutParams params = getWindow().getAttributes();
            params.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(params);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
        }
    }

    @Override
    public void onPushAddCid(String cid) {
        if (!TextUtils.isEmpty(cid)) {
            refreshRoomInfo();
            mFragmentMeeting.onPushAddCid(cid);
        }
    }

    @Override
    public void onPushByeCid(String cid) {
        if (!TextUtils.isEmpty(cid)) {
            refreshRoomInfo();
            mFragmentMeeting.onPushByeCid(cid);
        }
    }

    @Override
    public void onMainVideoDataInCall(long callToken, long pointer, int width, int height, char rotation, EngineSdkVideoPixelFormat format, long channelId) {
        super.onMainVideoDataInCall(callToken, pointer, width, height, rotation, format, channelId);
        mFragmentMeeting.onMainVideoDataInCall(pointer, width, height, rotation, channelId);
    }

    /**
     * 刷新房间信息
     */
    private void refreshRoomInfo() {
        if (!TextUtils.isEmpty(mRoomId)) {
            mFragmentMeeting.refreshRoomInfo(mRoomId);
        }
    }

    /**
     * 刷新流量
     */
    @Override
    protected void receiverSpeed(String rx, String tx) {
        super.receiverSpeed(rx, tx);
        mFragmentMeeting.receiverSpeed(rx, tx);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isLoading()) {
                dismissLoading();
                return true;
            }

            if (mFragmentMenu.isShowing()) {
                mFragmentMenu.hideDialog();
                return true;
            }

            if (!mFragmentMeeting.isHidden()) {
                popQuitLiveDialog();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 显示菜单
     */
    public void showMenu() {
        getSupportFragmentManager().beginTransaction().show(mFragmentMenu).commitAllowingStateLoss();
        mFragmentMenu.showDialog(FragmentMenu.FROM_MEETING);
    }

    /**
     * 弹出退出直播
     */
    public void popQuitLiveDialog() {
        new MaterialStyledDialog.Builder(this)
                .setHeaderColorInt(R.color.gray_transparent)
                .setDescription("Whether to quit live?")
                .setPositiveText("OK")
                .setNegativeText("CANCEL")
                .setCancelable(true)
                .onPositive((dialog, which) -> {
                    showLoading();
                    new Handler().postDelayed(() -> mCallHelper.quitConference(mRoomId), 500);
                })
                .show();
    }
}
